var isTest = true;

// var consoleJs = "./js/vconsole.min.js";
// var thisHref = window.location.href;
// loadJs(consoleJs, function() {
// 	vConsole = new VConsole();
// });


sui("#sui-back").click(function(){
	console.log(window.location.href);
	window.location.href ="main.html"
})

sui.Back = function(){
	window.location.href ="main.html"
}



// (function(doc, win) {
// 	var docEl = doc.documentElement,
// 		resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
// 		recalc = function() {
// 			var clientWidth = docEl.clientWidth;
// 			if (!clientWidth) return;
// 			if (clientWidth >= 2560) {
// 				docEl.style.fontSize = '200px';
// 			} else if (clientWidth <= 600) {
// 				docEl.style.fontSize = '32px';
// 			} else {
// 				//docEl.style.fontSize = 100 * (clientWidth / 1920) + 'px';
// 				docEl.style.fontSize = '14px';
// 			}
// 		};
// 	if (!doc.addEventListener) return;
// 	win.addEventListener(resizeEvt, recalc, false);
// 	doc.addEventListener('DOMContentLoaded', recalc, false);
// })(document, window);




function DebugPrint(print) {
	if (!isTest == true) return;
	if (typeof(print) == 'string') {
		console.log(print);
	} else {
		var divide = "-----------------------------------";
		for (var Key in print) {
			console.log(divide + Key + divide);
			console.log(JSON.stringify(print[Key]));
		}
	}
}

function getRandom(min, max) {
	var num = Math.floor(Math.random() * (min - max) + max);
	return num;
}

//判断是否为空
function IsNull(object) {
	if (!object || object == null || object == "" || object == "undefined" || object == 'null' || object == 'Null') {
		return true;
	} else {
		return false;
	}
}

function isNull(object) {
	if (!object || object == null || object == "" || object == "undefined" || object == 'null' || object == 'Null') {
		return true;
	} else {
		return false;
	}
}

//by 谭宇
function isNull2(object) {
	if (!object || object == null || object == "" || object == "undefined" || object == 'null' || object == 'Null' ||
		object == 0) {
		return true;
	} else {
		return false;
	}
}

function format(object) {
	if (!object || object == null || object == "" || object == "undefined" || object == 'null' || object == 'Null') {
		return "";
	} else {
		return object;
	}
}

//获得传入的?key=.value 参数
function getValue(key) {
	var str = decodeURI(window.location.search); //location.search是从当前URL的?号开始的字符串  
	//DebugPrint("页面参数:" + str);
	var value = "";
	if (str.indexOf(key) != -1) {
		var pos_start = str.indexOf(key) + key.length + 1;
		var pos_end = str.indexOf("&", pos_start);
		if (pos_end == -1) {
			value = str.substring(pos_start);
		} else {
			value = str.substring(pos_start, pos_end);
		}
	}
	return value;
}

function getFileName(path) {
	path = path || "";
	var pos = path.lastIndexOf("/");
	return path.substring(pos + 1);
}

//获得传入的?key=.value 参数
function getValueByUrl(key, url) {
	var strs = url.split("?");
	if (strs.length < 2) {
		return;
	}
	var str = decodeURI(strs[1]); //location.search是从当前URL的?号开始的字符串  
	DebugPrint("页面参数:" + str);
	var value = "";
	if (str.indexOf(key) != -1) {
		var pos_start = str.indexOf(key) + key.length + 1;
		var pos_end = str.indexOf("&", pos_start);
		if (pos_end == -1) {
			value = str.substring(pos_start);
		} else {
			value = str.substring(pos_start, pos_end);
		}
	}
	return value;
}


function formatDate(date) {
	//var date = new Date();
	var seperator1 = "-";
	var seperator2 = ":";
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	var hours = date.getHours();
	if (hours <= 9) {
		hours = "0" + hours;
	}
	var minutes = date.getMinutes();
	if (minutes <= 9) {
		minutes = "0" + minutes;
	}
	var seconds = date.getSeconds();
	if (seconds <= 9) {
		seconds = "0" + seconds;
	}

	var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
		" " + hours + seperator2 + minutes +
		seperator2 + seconds;
	return currentdate;
}


/** 
 * 获得当前日期时间（yyyy-MM-dd HH:mm:ss） 
 */
function getNowFormatDate() {
	var date = new Date();
	var seperator1 = "-";
	var seperator2 = ":";
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	var hours = date.getHours();
	if (hours <= 9) {
		hours = "0" + hours;
	}
	var minutes = date.getMinutes();
	if (minutes <= 9) {
		minutes = "0" + minutes;
	}
	var seconds = date.getSeconds();
	if (seconds <= 9) {
		seconds = "0" + seconds;
	}

	var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
		" " + hours + seperator2 + minutes +
		seperator2 + seconds;
	return currentdate;
}

/** 
 * 获得当前日期时间（yyyy-MM-dd ） 
 */
function getDateBegin() {
	var date = new Date();
	var seperator1 = "-";
	var seperator2 = ":";
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	var hours = date.getHours();
	if (hours <= 9) {
		hours = "0" + hours;
	}
	var minutes = date.getMinutes();
	if (minutes <= 9) {
		minutes = "0" + minutes;
	}
	var seconds = date.getSeconds();
	if (seconds <= 9) {
		seconds = "0" + seconds;
	}

	var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
	return currentdate;
}

/** 
 * 获得当前日期时间的前六个月时间（yyyy-MM-dd ） 
 */
function getDateEnd() {
	var date = new Date();
	date.setMonth(date.getMonth() - 6);
	var seperator1 = "-";
	var seperator2 = ":";
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	var hours = date.getHours();
	if (hours <= 9) {
		hours = "0" + hours;
	}
	var minutes = date.getMinutes();
	if (minutes <= 9) {
		minutes = "0" + minutes;
	}
	var seconds = date.getSeconds();
	if (seconds <= 9) {
		seconds = "0" + seconds;
	}

	var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
	return currentdate;
}

function getNowFormatDateNoSecends() {
	var date = new Date();
	var seperator1 = "-";
	var seperator2 = ":";
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	var hours = date.getHours();
	if (hours <= 9) {
		hours = "0" + hours;
	}
	var minutes = date.getMinutes();
	if (minutes <= 9) {
		minutes = "0" + minutes;
	}
	//	var seconds = date.getSeconds();
	//	if(seconds <= 9) {
	//		seconds = "0" + seconds;
	//	}

	var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
		" " + hours + seperator2 + minutes
	//+seperator2 + seconds
	;
	return currentdate;
}


function getRandomDateStr(endDate) {
	return formatDate(randomDate());
}


function randomDate() {
	var diff = 30 * 24 * 60 * 60 * 1000;
	var randomDiff = getRandom(0, diff);
	//console.log(randomDiff);
	// 截止日期
	var endDate = new Date();
	//console.log(endDate.getTime() - randomDiff);
	var date = new Date(endDate.getTime() - randomDiff);
	//console.log(getSimpleByDate(date));
	return date;
};

function getDateSimple(d) {
	if (!d || d.length == 0) {
		return "";
	}

	//去掉点后面的毫秒
	d = d.split('.').length > 0 ? d.split('.')[0] : d;
	//ios不兼容-
	d = d.replace(/\-/g, "/");
	var dt = new Date(d);
	return getSimpleByDate(dt).replace("00:00", "");
}

function getSimpleByDate(date) {
	//var date = new Date();
	var seperator1 = "/";
	var seperator2 = ":";
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	var hours = date.getHours();
	if (hours <= 9) {
		hours = "0" + hours;
	}
	var minutes = date.getMinutes();
	if (minutes <= 9) {
		minutes = "0" + minutes;
	}


	var currentdate = month + seperator1 + strDate +
		" " + hours + seperator2 + minutes
	//+seperator2 + seconds
	;
	return currentdate;
}

//计算天数差的函数
function DateDiff(sDate1, sDate2) { //sDate1和sDate2是2006-12-18格式  

	if (sDate1 != "" && sDate2 != "") {
		var aDate, oDate1, oDate2, iDays
		aDate = sDate1.split("-")
		oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]) //转换为12-18-2006格式  
		aDate = sDate2.split("-")
		oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
		iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24) //把相差的毫秒数转换为天数    

		return iDays
	}
}

function getSimpleDate(datestr) {
	datestr = datestr || "";
	return datestr.replace(":00.0", "")
}

//去掉毫秒
function getDateByReplaceMsec(datestr) {
	datestr = datestr || "";
	return datestr.replace(".0", "")
}

//判断今天是否生日 格式yyyy-mm-dd
function isBirthday(birthday) {
	//ios不兼容-
	birthday = birthday.replace(/\-/g, "/");

	var bir = new Date(birthday);
	var birMonth = bir.getMonth() + 1;
	var birDay = bir.getDate();

	var today = new Date();
	var month = today.getMonth() + 1;
	var day = today.getDate();

	DebugPrint(birMonth + "/" + birDay + "----" + month + "/" + day);

	if (birMonth = month && birDay == day) {
		return true;
	}
	return false;
}



function getPrivatePhone(phone) {
	if (isNull(phone)) {
		return "";
	}

	if (phone.length <= 4) {
		return "****";
	}

	var number = "";
	if (phone.length >= 11) {
		number = phone.substring(0, 3) + "****" + phone.substring(8, 11);
	} else if (phone.length >= 8) {
		number = phone.substring(0, 3) + "****" + phone.substring(8, phone.length);
	} else {
		number = phone.substring(0, 3) + "****";
	}
	return number;
}


function isContains(str, substr) {
	return new RegExp(substr).test(str);
}

/*根据出生日期算出年龄*/
function jsGetAge(strBirthday) {
	var returnAge;
	var strBirthdayArr = strBirthday.split("-");
	var birthYear = strBirthdayArr[0];
	var birthMonth = strBirthdayArr[1];
	var birthDay = strBirthdayArr[2];

	d = new Date();
	var nowYear = d.getFullYear();
	var nowMonth = d.getMonth() + 1;
	var nowDay = d.getDate();

	if (nowYear == birthYear) {
		returnAge = 0; //同年 则为0岁  
	} else {
		var ageDiff = nowYear - birthYear; //年之差  
		if (ageDiff > 0) {
			if (nowMonth == birthMonth) {
				var dayDiff = nowDay - birthDay; //日之差  
				if (dayDiff < 0) {
					returnAge = ageDiff - 1;
				} else {
					returnAge = ageDiff;
				}
			} else {
				var monthDiff = nowMonth - birthMonth; //月之差  
				if (monthDiff < 0) {
					returnAge = ageDiff - 1;
				} else {
					returnAge = ageDiff;
				}
			}
		} else {
			returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天  
		}
	}

	return returnAge; //返回周岁年龄  

}

//深层拷贝
function deepCopy(obj) {
	if (typeof obj != 'object') {
		return obj;
	}
	var newobj = {};
	for (var attr in obj) {
		newobj[attr] = deepCopy(obj[attr]);
	}
	return newobj;
}

//从文件名获取文件类型返回类型图片
function getImageByFileType(fileName) {
	var fileType = "file_other.png";

	var fileTypes = [{
			img: "file_zip.png",
			names: ".zip.rar"
		},
		{
			img: "file_word.png",
			names: ".doc.docx.wps"
		},
		{
			img: "file_excel.png",
			names: ".xls.xlsx"
		},
		{
			img: "file_ppt.png",
			names: ".ppt.pptx"
		},
		{
			img: "file_pdf.png",
			names: ".pdf"
		},
		{
			img: "file_flash.png",
			names: ".fla"
		},
		{
			img: "file_video.png",
			names: ".mp4.avi.mob"
		},
		{
			img: "file_music.png",
			names: ".mp3.aar"
		},
		{
			img: "file_txt.png",
			names: ".txt"
		},
		{
			img: "file_img.png",
			names: ".png.jpg.jpeg.bmp.gif"
		},
		{
			img: "file_html.png",
			names: ".html.js.css"
		},
	];

	//获得后缀名
	var ext = null;
	var name = fileName.toLowerCase();
	var i = name.lastIndexOf(".");
	if (i > -1) {
		var ext = name.substring(i);
	}

	if (ext) {
		for (var index = 0; index < fileTypes.length; index++) {
			if (fileTypes[index].names.indexOf(ext) >= 0) {
				fileType = fileTypes[index].img;
				break;
			}
		}
	}
	//	DebugPrint("name:" + fileName + "|type:" + fileType)
	return fileType;
}


function reLaunch(url, params) {
	//if (!syberh.os.syberos  && !syberh.os.syberos) {
	window.location = url;
	window.event.returnValue = false;
	return;
	//} 

	if (syberh.os.syberos == true) {
		url = url.replace("../", "");
		DebugPrint("重新打开:" + url);
		syberh.router.reLaunch({
			url: url,
			data: params,
			success: function(result) {
				DebugPrint('reLaunch success:', result);
				DebugPrint("reLaunch pages:" + syberh.router.getCurrentPages());
			},
			fail: function(error) {
				DebugPrint('reLaunch fail: ', error.code, error.msg);
			}
		});
		return;
	}
}

function openWindow(url, params) {
	if (!syberh.os.syberos && !syberh.os.syberos) {
		window.location = url;
		//window.event.returnValue = false;
		return;
	}

	if (syberh.os.syberos == true) {

		url = url.replace("../", "");
		//syberos都是从www目录下的相对路径
		DebugPrint("syberh.os.syberos:" + syberh.os.syberos);
		DebugPrint("index:" + url.indexOf("index.html"));
		DebugPrint("login:" + url.indexOf("login.html"));
		DebugPrint("webs/:" + url.indexOf("webs/"));

		if (syberh.os.syberos && url.indexOf("index.html") != 0 && url.indexOf("login.html") != 0 && url.indexOf("webs/") !=
			0) {
			url = "webs/" + url;
		}

		DebugPrint("openurl:" + url);

		//syberh.router.redirectTo({
		syberh.router.navigateTo({
			url: url,
			data: params,
			success: function(result) {
				DebugPrint('navigateTo success:', url);
				DebugPrint("pages:" + syberh.router.getCurrentPages());
			},
			fail: function(error) {
				DebugPrint('navigateTo fail: ', error.code, error.msg);
			}
		});
		return;
	}
}

function redirectTo(url, params) {
	if (!syberh.os.syberos) {
		window.location = url;
		//window.event.returnValue = false;
		return;
	}

	if (syberh.os.syberos == true) {
		// DebugPrint("pages:"+ syberh.router.getCurrentPages());
		// DebugPrint("url:"+ url);
		url = url.replace("../", "");
		syberh.router.redirectTo({
			url: url,
			data: params,
			success: function(result) {
				DebugPrint('redirectTo success:', result);
				if (params.refresh == true) {
					syberh.router.reload({
						success: function(result) {
							DebugPrint('reload success:', result);
						},
						fail: function(error) {
							DebugPrint('reload fail: ', error.code, error.msg);
						}
					})
				}
			},
			fail: function(error) {
				DebugPrint('fail: ', error.code, error.msg);
			}
		});
		return;
	}
}

function navigateBack(backNum, params) {
	backNum = backNum || 1;
	DebugPrint("navigateBack:" + backNum);

	backNum = 0 - backNum;
	DebugPrint("go:" + window.history.length);
	window.history.go(backNum);
	return false;


	// if (syberh.os.syberos == true) {
	// 	//params = params || {};
	// 	//var parmStr = JSON.stringify(params);
	// 	//localStorage.setItem("navigateback-params", parmStr)
	// 	syberh.router.navigateBack({
	// 		delta: backNum,
	// 		success: function(result) {
	// 			DebugPrint('navigateBack success:', result);
	// 		},
	// 		fail: function(error) {
	// 			DebugPrint('navigateBack fail: ', error.code, error.msg);
	// 		}
	// 	})
	// }
}

function getNavigateBackParams() {
	var navStr = localStorage.getItem("navigateback-params");
	DebugPrint('getNavigateBackParams:', navStr);
	var params = {};
	try {
		params = JSON.parse(navStr);
	} catch (e) {
		DebugPrint(e);
	}
	//localStorage.setItem("navigateback-params","{}")
	return params;
}

function reload() {
	if (syberh.os.syberos) {
		syberh.router.reload({
			success: function(result) {
				DebugPrint('reload success', result);
			},
			fail: function(error) {
				DebugPrint('reload fail: ', error.code, error.msg);
			}
		})
	} else {
		location.reload();
	}
}

//默认返回键关闭窗口
sui.ready(function() {
	sui("#sui-back").click(function() {
		window.location.href ="main.html"
	})
})


function commonBack() {
	window.history.back(-1);
}


function setTitle(str) {
	sui(".sui-bar .sui-title").html(str);
}

function isChinese(temp) {
	var patrn = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/gi;
	if (!patrn.exec(temp)) {
		return false;
	} else {
		return true;
	}
}

function openWorkDetail(work, workType, floor) {
	var actionURL = work.actionURL || work.actionurl;
	var processDefName = work.processDefName || work.processdefname; //getValueByUrl('formId', actionURL);
	var isStudio = false; //是否studio流程
	isStudio = processDefName.split(".").length > 1 ? true : false;

	var param = {
		id: work.processInstID || work.processinstid,
		name: work.processChName,
		workItemId: work.workItemID,
		processDefName: processDefName,
		type: workType || 0,
		activityDefID: work.activityDefID,
		isStudio: isStudio,
	}

	//DebugPrint("是否studio流程:" + isStudio + "|" + processDefName);
	//url = apiManage.makeUrl(isStudio ? "work_detail_studio.html" : "work_detail.html", param);

	url = (floor || "") + "work_detail.html";
	url = apiManage.makeUrl(url, param);
	DebugPrint(url);
	openWindow(url);

}

var myStorage = new MyStorage();


var STORAGE = {
	SALARY_VALID: "savary_valid",
	FAV_CHANGED: "fav-changed", //常用联系人修改
	MAIN_FAV_CHANGED: "main-fav-changed", //常用联系人修改
	WORK_CHANGED: "work-changed", //常用联系人修改
	MAIN_WORK_CHANGED: "main-work-changed", //常用联系人修改


	MAIL_CHANGE: "mail-change", //邮件修改
}



function MyStorage() {
	var _self = this;

	this.saveItem = function(name, value) {
		var saveStr = JSON.stringify(value);
		DebugPrint(saveStr.length);
		if (!syberh.os.syberos) {
			localStorage.setItem(name, saveStr);
		} else {
			syberh.storage.setItem({
				key: name,
				value: saveStr,
				success: function(result) {
					DebugPrint('setItem success', result)
				},
				fail: function(error) {
					DebugPrint('setItem fail: ', error.code, error.msg)
				}
			})
		}
	};

	this.getItem = function(name, callback) {
		var getStr = "";
		if (!syberh.os.syberos) {
			getStr = localStorage.getItem(name);
			try {
				getStr = JSON.parse(getStr);
			} catch (e) {
				DebugPrint("getItem解析失败:" + e.message)
			}
			if (callback) {
				callback(getStr);
			}
		} else {
			syberh.storage.getItem({
				key: name,
				success: function(result) {
					if (result && result.value) {
						getStr = result.value;
						try {
							getStr = JSON.parse(getStr);
						} catch (e) {
							DebugPrint("getItem解析失败:" + e.message)
						}
						if (callback) {
							callback(getStr);
						}
					} else {
						callback("")
					}
				},
				fail: function(error) {
					DebugPrint('getItem解析失败 fail: ', error.code, error.msg)
				}
			})
		}
	}

}

// <br/> 转 textArea换行符
function decodeTextAreaString(str) {
	str = str || "";
	var reg = new RegExp("<br/>", "g");
	str = str.replace(reg, "\n");
	var reg2 = new RegExp("</br>", "g");
	str = str.replace(reg2, "\n");
	var reg3 = new RegExp("<br>", "g");
	str = str.replace(reg3, "\n");
	return str;
}
// textArea换行符转<br/>
function encodeTextAreaString(str) {
	str = str || "";
	var reg = new RegExp("\n", "g");
	str = str.replace(reg, "<br/>");
	return str;
}


function setScrollY(id1, id2) {
	var offset = sui.offset(document.getElementById(id1));
	var offset2 = null;
	if (id2) {
		offset2 = sui.offset(document.getElementById(id2));
	} else {
		offset2 = sui.winInfo;
	}

	var id = "#" + id1;
	var height = (offset2.top || offset2.height) - offset.top;

	console.log("height:" + height);

	if (height > 0) {
		sui(id).scrollY(height);
	}
}

function loadJs(url, callback) {
	var script = document.createElement('script');
	script.type = "text/javascript";
	if (typeof(callback) != "undefined") {
		if (script.readyState) {
			script.onreadystatechange = function() {
				if (script.readyState == "loaded" || script.readyState == "complete") {
					script.onreadystatechange = null;
					callback();
				}
			}
		} else {
			script.onload = function() {
				callback();
			}
		}
	}
	script.src = url;
	document.body.appendChild(script);
}


function copyToClipboard(txt) {
	if (window.clipboardData) {
		window.clipboardData.clearData();
		clipboardData.setData("Text", txt);
		alert("复制成功！");
	} else if (navigator.userAgent.indexOf("Opera") != -1) {
		window.location = txt;
	} else if (window.netscape) {
		try {
			netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
		} catch (e) {
			alert("被浏览器拒绝！\n请在浏览器地址栏输入'about:config'并回车\n然后将 'signed.applets.codebase_principal_support'设置为'true'");
		}
		var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
		if (!clip)
			return;
		var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
		if (!trans)
			return;
		trans.addDataFlavor("text/unicode");
		var str = new Object();
		var len = new Object();
		var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
		var copytext = txt;
		str.data = copytext;
		trans.setTransferData("text/unicode", str, copytext.length * 2);
		var clipid = Components.interfaces.nsIClipboard;
		if (!clip)
			return false;
		clip.setData(trans, null, clipid.kGlobalClipboard);
		alert.log("复制成功！");
	}
}
